var Permission = function(){
	var validator = null;
	var ztreeObj = null,menuZtreeObj = null;
	var roleGridObj = null;
	var userGirdObj = null;
	var permissionValidator = null
	function refreshPermissionTree(id){
		SysPermissionController.getAllPermissionTreeById(function(trees){
			ZtreeUtil.initTree("ztree",trees,{
				onClick:function(event, treeId, treeNode){
					if(treeNode.type == "permission"){
						permissionBaseInfoView(treeNode.id);
					}else{
						return false;
					}
				},
				beforeClick:function(treeId, treeNode, clickFlag){
					if(treeNode.type == "permission"){
						return true;
					}else{
						return false;
					}
				}
			},{
				data:{
					key:{
						name: "text",
		    			url: null
					}
				}
			},{

				context:[{
	                id: "addPermission",
	                label: "新增权限",
	                visible: function(NODE,TREE_OBJ){
	                	if(NODE.type=="module"){
	                		return true;
	                	}else{
	                		return false;
	                	}
	                },
	                action: function(NODE, TREE_OBJ){
	                	newPermissionBaseInfo(NODE.id);
	                }
	            },{
	                id: "editPermission",
	                label: "编辑权限",
	                visible: function(NODE,TREE_OBJ){
	                	if(NODE.type=="permission"){
	                		return true;
	                	}else{
	                		return false;
	                	}
	                },
	                action: function(NODE, TREE_OBJ){
	                	permissionBaseInfoView(NODE.id);
	                }
	            },{
	                id: "delPermission",
	                label: "删除权限",
	                visible: function(NODE,TREE_OBJ){
	                	if(NODE.type=="permission"){
	                		return true;
	                	}else{
	                		return false;
	                	}
	                },
	                action: function(NODE, TREE_OBJ){
	                	Message.confirm('确认删除权限【'+NODE.text+'】吗？', function(index){
	                		SysPermissionController.removePermissionById(NODE.id,function(value){
	                			if(value){
	                				Message.success("删除成功！");
	                				ZtreeUtil.removeNodeRefreshTree('ztree',NODE);
	                				$("#permission-tab").hide();
	                			}else{
	                				Message.error("删除失败！");
	                			}
	                			
	                			Message.close(index);
	                		});
	        				 
	                    });
	                }
	            }]
			
				
			});
			ztreeObj = ZtreeUtil.getZtreeObj('ztree');
			if(id){
				//保持选中前状态
				var node = ztreeObj.getNodeByParam("id",id);
				ztreeObj.selectNode(node);
			}
		});
		
		
	}
	
	function refreshMenuTree(){
		var permissionId = $("#id").val(); 
		
		if(permissionId == ""){
			Message.tips("请先保存权限基本信息","#has-menu",{layout:'right'});
			$('#has-menu').one('shown', function (e) {
				$("#tabs-has-menu").removeClass("active");
			});
			return false;
		}
		$("#tabs-has-menu").addClass("active");
		SysPermissionController.showPermissionOwnMenuTree(permissionId,function(retMap){
			if(retMap){
				var trees = retMap["menuTree"];
				var ownMenus = retMap["ownMenus"];
				ZtreeUtil.initTree("menuTree",trees,{
				},{
					data:{
						key:{
							name: "text",
			    			url: null
						}
					},check: {
						enable: true
					}
				});
				menuZtreeObj =  ZtreeUtil.getZtreeObj('menuTree');
				
				for (var i=0; i<ownMenus.length;  i++) {
					menuZtreeObj.checkNode(menuZtreeObj.getNodeByParam("id",ownMenus[i] , null), true, true);
				}
				
			}
			
		});
	}
	
	function newPermissionBaseInfo(moduleId){
		AppUtils.validatorRemoteCache("#name");
		$("#permission-tab").show();
		$('#permissionTab a:first').tab('show');
		$("#has-role").hide();
		$("#has-user").hide();
		AppUtils.clearForm("#editPermissonForm");
		$("#permissionModuleId").val(moduleId);
		
	}
	
	function permissionBaseInfoView(permissionId){
		AppUtils.validatorRemoteCache("#name");
		AppUtils.clearForm("#editPermissonForm");
		$("#permission-tab").show();
		$("#has-role").show();
		$("#has-user").show();
		$('#permissionTab a:first').tab('show');
		SysPermissionController.getPermissionInfoById(permissionId,function(permissionInfo){
			if(permissionInfo){
				$.each(permissionInfo, function(key, value) {
					if($("#"+key).length >0){
						dwr.util.setValue(key, value);
					}
				});
			}
		})
	}
	
	
	
	return{
		initPermissionTree:function(){
			refreshPermissionTree();
			permissionValidator=$("#editPermissonForm").validate({
				onkeyup: function(element, event){
					if ($(element).attr('name') == "name") {
                        return false; 
                    } else { 
                        if ( event.which === 9 && this.elementValue( element ) === "" ) {
                            return;
                        } else if ( element.name in this.submitted || element === this.lastElement ) {
                            this.element( element );
                        }
                    }
				},
				rules:{
					name:{required:true,maxlength:10,remote:{
						url:contextPath+'/sys/permission/checkIsNameExist.htm',
						type:'post',
						cache:false,
						dataType:'json',
						data:{
							id:function(){
								return $("#id").val();
							},
							moduleId:function(){
								return $("#permissionModuleId").val();
							}
						}
					}},
					code:{required:true,maxlength:40}
				},
				messages:{
					name:{remote:jQuery.format("权限名称【{0}】已经存在")}
				}
			});
		},
		refreshPermissionTree:function(){
			refreshPermissionTree();
		},
		savePermissionInfo:function(){
			permissionValidator.form();
			if (!permissionValidator.valid()) {
				return false;
			}
			var permissionInfo = dwr.util.getFormValues('editPermissonForm');
			SysPermissionController.savePermissionInfo(permissionInfo,$("#permissionModuleId").val(),function(permissionInfoDTO){
				if(permissionInfoDTO){
					Message.success("保存成功");
					$("#id").val(permissionInfoDTO.id);
					refreshPermissionTree(permissionInfoDTO.id);
				}else{
					Message.error("保存失败");
				}
			});
		},
		reloadRoleGird:function(){
			var permissionId = $("#id").val();
			if(roleGridObj == null){
				roleGridObj= $.fn.bsgrid.init('roleTable', {
		            url:contextPath+"/sys/permission/getRoleList.htm",
		            otherParames:{"permissionId":permissionId},
		            pageSizeSelect: true,
		            stripeRows: true,
		            rowSelectedColor:false,
		            pageSize: 10
					
		        });
			}else{
				roleGridObj.search({"permissionId":permissionId});
			}
		},
		reloadUserGird:function(){
			var permissionId = $("#id").val(); 
			if(userGirdObj == null){
				userGirdObj= $.fn.bsgrid.init('userTable', {
		            url:contextPath+"/sys/permission/getUserList.htm",
		            otherParames:{"permissionId":permissionId},
		            pageSizeSelect: true,
		            stripeRows: true,
		            rowSelectedColor:false,
		            pageSize: 10
					
		        });
			}else{
				userGirdObj.search({"permissionId":permissionId});
			}
		},
		reloadMenuTree:function(){
			refreshMenuTree();
		},
		saveMenuRelation:function(){
			var permissionId = $("#id").val(); 
			var nodes = menuZtreeObj.getCheckedNodes(true);
			var menuIds =new Array();
			$.each(nodes,function(index,element){
				if(element.type == "menu"){
					menuIds.push(element.id);
				}
			});
			SysPermissionController.savePermissionOwnMenu(permissionId,menuIds,function(data){
				if(data){
					Message.success("保存成功");
				}
			});
		}
		
		
		
	}
}();